import logging

import redis

logger = logging.getLogger(__name__)


class RedisBase(object):

    def __init__(self, host, port, db_index, password):
        pool = redis.ConnectionPool(host=host, port=port, db=db_index, password=password, decode_responses=True)
        self.db_conn = redis.Redis(connection_pool=pool)

    def lpush(self, listname, data):
        # 将数据插入到集合
        self.db_conn.lpush(listname, data)

    def hset(self, db, key, value):
        self.db_conn.hset(db, key, value)

    def hget(self, db, key):
        return self.db_conn.hget(db, key)

    def delete(self, key):
        return self.db_conn.delete(key)

    def hkeys(self, name):
        return self.db_conn.hkeys(name)

    def hgetall(self, name):
        return self.db_conn.hgetall(name)

    def llen(self, listname):
        len = self.db_conn.llen(listname)
        return len

    def batch_lpop(self, key, n):
        p = self.db_conn.pipeline()
        p.lrange(key, 0, n - 1)
        p.ltrim(key, n, -1)
        data = p.execute()
        return data

    def rpop(self, listname):
        if self.db_conn.llen(listname) != 0:  # 判断redis中的 list是否有数据
            str_data = self.db_conn.rpop(listname)  # 连接的时候已经默认解码了
            return str_data

    def close_connect(self):
        # 关闭连接
        self.db_conn.connection_pool.disconnect()
        logger.info("redis连接已经被关闭")
